import glob
import json
import os
import shutil
import threading
import time
import zipfile
from dwebsocket.decorators import accept_websocket, require_websocket
from django.views.decorators.csrf import csrf_exempt
from tqdm import tqdm
from django.http import JsonResponse, FileResponse
from django.shortcuts import render

# Create your views here.
from file_share import settings

can_view = ['bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf',
            'ufo', 'eps', 'ai', 'raw', 'wmf', 'webp', 'avif', 'apng', 'pdf', 'jpeg', 'txt', 'text',
            'BMP', 'JPG', 'PNG', 'TIF', 'GIF', 'PCX', 'TGA', 'EXIF', 'FPX', 'SVG', 'PSD', 'CDR', 'PCD', 'DSF',
            'UFO', 'EPS', 'AI', 'RAW', 'WMF', 'WEBP', 'AVIF', 'APNG', 'PDF', 'TXT', 'TEXT'
            ]
jin_du_tiao = float()
is_over = False  # 判断是否压缩完成


def folder_show(request):
    fds = dict()
    try:
        path = request.GET['curr_path']
    except:
        path = os.path.join(settings.BASE_DIR, 'files')

    def folders_get(path, name, folders):
        i_path = os.path.join(path, name)
        if os.path.isdir(i_path):
            folders.append(i_path)
            for i in os.listdir(i_path):
                folders_get(i_path, i, folders)

    for i in os.listdir(path):
        folders = []
        if os.path.isdir(os.path.join(path, i)):
            fds.update({i: folders})
        folders_get(path, i, folders)

    return JsonResponse({'fds': fds})


def show(request):
    fs = dict()
    try:
        path = request.GET['folder_name']
        add_return = request.GET['add_return']
    except:
        add_return = False
        path = os.path.join(settings.BASE_DIR, 'files')
    ######### 得到所有的文件夹及对应路径 part 1 ########################
    folder_paths = dict()

    def folders_get(path, name, folders):
        i_path = os.path.join(path, name)
        if os.path.isdir(i_path):
            folders.append(i_path)
            for i in os.listdir(i_path):
                folders_get(i_path, i, folders)

    ################################################################
    for i in os.listdir(path):
        i_path = os.path.join(path, i)
        type_file = '文件夹' if os.path.isdir(i_path) else os.path.splitext(i_path)[1][1:].upper() if \
        os.path.splitext(i_path)[1] else 'FILE'
        fs.update({i: [
            i_path,
            os.stat(i_path),
            type_file,
            i_path.split('files')[1]
        ]})
        ###### 得到所有的文件夹及对应路径 part 2 ####################

        folders = []
        if os.path.isdir(os.path.join(path, i)):
            folder_paths.update({i: folders})
        folders_get(path, i, folders)
        ########################################################
    last_path = ''
    for i in path.split('\\')[0:-1]:
        last_path += i + '\\'
    last_path = last_path[0:-1]  # 删除最后一个 \
    if last_path.split('\\')[-1] != 'files':
        last_path += '&add_return=True'
    try_f = {'zip': [{'vvsd': [{'fbgb': ['空']}]}, {'wwwww': ['空']}]}
    return render(request, 'index.html',
                  {'fs': {i: j for i, j in sorted(fs.items())}, 'can_view': can_view, 'add_return': add_return, 'last_path': last_path,
                   'folder_paths': try_f})
    # return JsonResponse(
    #     {'fs': fs, 'can_view': can_view, 'add_return': add_return, 'last_path': last_path, 'folder_paths': try_f})


# os.path.isfile
def render_upload(request):
    # fs = [i for i in os.listdir(os.path.join(settings.BASE_DIR, 'files'))]
    return render(request, 'dwebsocket.html')


old_file_uuid = None
def receive_upload_to_local(request):
    """
    存储数据
    :param request:
    :return:
    """
    global old_file_uuid
    if request.method == "POST":
        st = time.time()
        for file in dict(request.FILES)['file_data']:
            load = time.time()
            old_name = request.POST['fileName']
            file_uuid = request.POST['file_uuid']
            print(file_uuid,old_file_uuid)
            # suffix = old_name.rsplit(".")[1]
            # img_name = int(time.time())
            dir = os.path.join(os.path.join(settings.BASE_DIR, 'files'), old_name)
            # dir = os.path.join(os.path.join(settings.BASE_DIR, 'files'), str(img_name) + '.' + suffix)
            get_info = time.time()
            cnt = 1
            while os.path.exists(dir) and old_file_uuid != file_uuid:
                file_name = os.path.splitext(old_name)[0] + '(' + str(cnt) + ')'
                file_type = os.path.splitext(old_name)[1]
                dir = os.path.join(os.path.join(settings.BASE_DIR, 'files'), file_name + file_type)
                cnt += 1
            old_file_uuid = file_uuid
            destination = open(dir, 'ab+')
            open_file = time.time()
            for i in file:
                destination.write(i)
            destination.close()
            done = time.time()
            b = load - st
            print('------------------------------------------------------------------------------------')
            print('------------------------------------------------------------------------------------')
            print('------------------------------------------------------------------------------------')
            print('加载时间：', b)
            print('获取request信息时间', get_info - load)
            print('打开本地文件时间', open_file - get_info)
            print('写入文件时间', done - open_file)
        return JsonResponse({"status": True})
    else:
        return JsonResponse({"status": False, "error": "请求错误"})


def creat_new_folder(request):
    if request.method == "POST":
        curr_path = request.POST['curr_path']
        creat_folder_path_ori = ''
        for i in curr_path.split('\\')[0:-1]:
            creat_folder_path_ori += i + '\\'
        creat_folder_path_ori += '新建文件夹'
        creat_folder_path = creat_folder_path_ori

        cnt = 1
        while True:
            print(creat_folder_path_ori)
            if os.path.exists(creat_folder_path):
                creat_folder_path = creat_folder_path_ori + '(' + str(cnt) + ')'
                cnt += 1
            else:
                break
        os.system('mkdir "%s"' % creat_folder_path)
        print(creat_folder_path)
        return JsonResponse({"status": '200'})
    else:
        return JsonResponse({"status": '404', "error": "请求错误"})


def rename_folder(request):
    if request.method == "POST":
        curr_path = request.POST['curr_path']
        new_name = request.POST['new_name']
        origin_path = ''
        for i in curr_path.split('\\')[0:-1]:
            origin_path += i + '\\'
        new_path = origin_path + new_name
        if os.path.exists(new_path):
            return JsonResponse({"status": '404', "error": "文件名已存在"})

        os.rename(curr_path, new_path)
        return JsonResponse({"status": '200'})
    else:
        return JsonResponse({"status": '404', "error": "请求错误"})


def del_file(request):
    if request.method == "POST":
        curr_path = request.POST['curr_path']
        if os.path.isfile(curr_path):
            os.system('del "%s"' % curr_path)
        else:
            os.system('rd /s /q "%s"' % curr_path)
        return JsonResponse({"status": '200'})
    else:
        return JsonResponse({"status": '404', "error": "请求错误"})


@csrf_exempt
@accept_websocket
def folder_to_zip(request):
    time.sleep(0.5)
    while True:
        if is_over:
            request.websocket.send(str('is_over'))
            break
        time.sleep(0.03)
        print(jin_du_tiao)
        request.websocket.send(str('%.2f' % jin_du_tiao))


def download_file(request):
    global jin_du_tiao, is_over
    file_path = request.GET['file_path']
    try:
        if os.path.isfile(file_path):
            f = open(file_path, 'rb')
            r = FileResponse(f, as_attachment=True, filename=None)
            return r
        else:
            is_over = False
            # shutil.copytree(file_path,)
            file_news = file_path + '.zip'  # 压缩后文件夹的名字
            z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)  # 参数一：文件夹名
            ##############################
            x = float()  # 文件总个数

            def visitdir(path):
                if not os.path.isdir(path):
                    print('Error: "', path, '" is not a directory or does not exist.')
                    return
                else:
                    nonlocal x
                    try:
                        for lists in os.listdir(path):
                            sub_path = os.path.join(path, lists)
                            if os.path.isdir(sub_path):
                                visitdir(sub_path)
                            else:
                                x += 1
                                print('No.', x, ' ', sub_path)
                    except Exception as ee:
                        print(ee)
                        pass

            visitdir(file_path)
            ##############################

            for dirpath, dirnames, filenames in os.walk(file_path):
                fpath = dirpath.replace(file_path, '')  # 这一句很重要，不replace的话，就从根目录开始复制
                fpath = fpath and fpath + os.sep or ''  # 语法没看懂 照搬来的 可以实现当前文件夹以及包含的所有文件的压缩
                for filename in filenames:
                    s = time.time()
                    z.write(os.path.join(dirpath, filename), fpath + filename)
                    jin_du_tiao += float(1 / x * 100)

                    print('----------------------------------')
                    print(filename, time.time() - s)
                    # print('压缩成功')
            z.close()
            f = open(file_news, 'rb')
            r = FileResponse(f, as_attachment=True, filename=None)
            jin_du_tiao = float()
            is_over = True

            #  但下载文件夹的时候将文件夹打包成zip然后return出去以完成下载操作 之后多线程将zip包删掉
            def remove_zip(zip_path):
                while True:
                    try:
                        os.remove(zip_path)
                        print('Done')
                        break
                    except Exception as e:
                        pass

            threading.Thread(target=remove_zip, args=(file_news,)).start()
            return r
    except Exception as e:
        return JsonResponse({"status": '404', "error": "请求错误%s" % str(e)})


#################################################################################################
# from django.shortcuts import render
# from dwebsocket.decorators import accept_websocket, require_websocket
from django.http import HttpResponse


@accept_websocket
def echo(request):
    # for i in range(200):
    #     time.sleep(0.001)
    #     request.websocket.send('gdfgfjsfhgs')
    if not request.is_websocket():  # 判断是不是websocket连接
        try:  # 如果是普通的http方法
            message = request.GET['message']
            return HttpResponse(message)
        except:
            return render(request, 'index.html')
    else:
        for message in request.websocket:
            # request.websocket.send(message)  # 发送消息到客户端
            print(message)
            w_file = open('./111.jpg', 'ab+')
            w_file.write(message)
